<template>
  <div class="box">
    <div class="searcharea">
      <!-- 搜索 -->
      <el-row>
        <el-col :span="24">
          <div class="query">
            <el-form :inline="true" :model="queryProductBillParam" class="demo-form-inline">
              <el-form-item label="产品名称">
                <el-input
                  v-model="queryProductBillParam.ProductBillName"
                  placeholder="请输入"
                  clearable
                  style="width: 270px"
                />
              </el-form-item>

              <el-form-item>
                <el-button type="primary" :icon="Search" @click="SearchProductBill()">搜索</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </div>

    <div class="box">
      <el-row>
        <el-col :span="4" class="leftcontentarea grid-content ep-bg-purple">
          <span>分类列表 </span>
          <el-divider content-position="left">快速选择</el-divider>
          <div class="grid-content ep-bg-purple x-scrollbar">
            <el-scrollbar max-height="400px">
              <el-tree
                ref="treeRef"
                style="max-width: 600px"
                class="filter-tree"
                :data="treeData"
                default-expand-all
                :filter-node-method="filterNode"
                @node-click="handleTreeNodeClick"
              />
            </el-scrollbar>
          </div>
        </el-col>
        <el-col :span="20" class="rightcontentarea">
          <div class="rightcontentareatable">
            <!-- 功能按钮 -->
            <el-row>
              <el-col :span="24">
                <div class="functionbutton">
                  <el-button type="primary" plain @click="addProductBill()">添加</el-button>
                  <el-button type="danger" plain @click="batchDeletionProductBill()">批量删除</el-button>
                </div>
              </el-col>
            </el-row>
            <!-- 数据表格 -->
            <el-row>
              <el-col :span="24">
                <div>
                  <el-table
                    v-loading="tableloading"
                    :data="tableData"
                    border
                    style="width: 100%"
                    max-height="400px"
                    :selection="selectedRows"
                    @selection-change="handleSelectionChange"
                    @row-click="getRowkey"
                    row-key="id"
                    show-overflow-tooltip
                    empty-text="暂无数据"
                  >
                    <el-table-column type="selection" width="55" />
                    <el-table-column type="index" label="序号" width="60" />
                    <el-table-column prop="productBillNo" label="产品编码" width="180">
                      <template #default="scope">
                        <el-button type="text" @click="handleProductBillNoClick(scope.row.id)">
                          {{ scope.row.productBillNo }}
                        </el-button>
                      </template>
                    </el-table-column>
                    <el-table-column prop="productBillName" label="产品名称" width="180" />
                    <el-table-column prop="model" label="型号" width="180" />
                    <el-table-column prop="dimensions" label="尺寸" width="180" />
                    <el-table-column prop="weight" label="重量" width="180" />
                    <el-table-column prop="color" label="颜色" width="180" />
                    <el-table-column prop="productClassify.productClassifyName" label="款型" width="180" />
                    <el-table-column prop="measuringUnit.measuringUnitName" label="单位" width="180" />
                    <el-table-column prop="shellMaterial" label="外壳材质" width="180" />
                    <el-table-column prop="batteryCapacity" label="电池容量" width="180" />
                    <el-table-column prop="ratedCapacity" label="额定容量" width="180" />
                    <el-table-column prop="maxOutputPower" label="最大输出功率" width="180" />
                    <el-table-column prop="chargingProtocol" label="充电协议" width="180" />
                    <el-table-column prop="batteryType" label="电池类型" width="180" />
                    <el-table-column prop="voltage" label="电压" width="180" />
                    <el-table-column prop="creator" label="创建人" width="180" />
                    <el-table-column prop="updator" label="修改人" width="180" />
                    <el-table-column prop="createtime" label="创建时间" width="180" :formatter="formatColumnTime" />
                    <el-table-column prop="updateDate" label="更新时间" width="180" :formatter="formatColumnTime" />
                    <el-table-column fixed="right" label="操作" width="100">
                      <template #default="scope">
                        <el-button type="danger" plain size="small" @click="DeleteProductBillSingle(scope.row.id)">
                          删除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-col>
            </el-row>

            <!-- 分页 -->
            <el-row>
              <el-col :span="24">
                <div class="demo-pagination-block" style="display: flex; justify-content: flex-end">
                  <el-config-provider :locale="zhCn">
                    <el-pagination
                      v-model:current-page="queryProductBillParam.PageIndex"
                      v-model:page-size="queryProductBillParam.PageSize"
                      :page-sizes="[100, 200, 300, 400]"
                      :small="false"
                      :disabled="false"
                      :background="true"
                      layout="total, sizes, prev, pager, next, jumper"
                      :total="queryProductBillParam.totalCount"
                      @size-change="handleSizeChange"
                      @current-change="handleCurrentChange"
                    >
                    </el-pagination>
                  </el-config-provider>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 功能按钮实现 -->
    <!-- 添加 -->
    <div>
      <!-- 添加产品 -->
      <el-dialog
        v-model="centerDialogVisible"
        :fullscreen="isFullScreen"
        width="72%"
        append-to-body
        :show-close="false"
        :before-close="CreateProductBillhandleClose"
      >
        <template #header="{ titleId, titleClass }">
          <div class="my-header">
            <span :id="titleId" :class="titleClass">添加产品</span>
            <div class="header-buttons">
              <el-icon @click="toggleFullScreen" class="icon-button">
                <FullScreen v-if="!isFullScreen" /><CopyDocument v-else />
              </el-icon>
              <el-icon @click="CreateProductBillhandleClose" class="icon-button full-screen-btn"><Close /></el-icon>
            </div>
          </div>
        </template>

        <el-scrollbar :max-height="maxHeight + 'px'">
          <div>
            <el-row>
              <el-col :span="24">
                <el-form
                  :inline="true"
                  ref="CreateProductBillFormRef"
                  :model="CreateProductBillForm"
                  label-width="auto"
                  class="demo-form-inline"
                  :rules="CreateProductBillRules"
                >
                  <el-form-item label="产品编码" prop="ProductBillNo">
                    <el-input
                      v-model="CreateProductBillForm.ProductBillNo"
                      placeholder="不输入则自动生成"
                      style="width: 270px"
                    >
                    </el-input>
                  </el-form-item>
                  <el-form-item prop="ProductBillName" label="产品名称">
                    <el-input
                      v-model="CreateProductBillForm.ProductBillName"
                      placeholder="请输入产品产品名称"
                      style="width: 270px"
                    >
                    </el-input>
                  </el-form-item>

                  <el-form-item label="尺寸" prop="Dimensions">
                    <el-input v-model="CreateProductBillForm.Dimensions" placeholder="请输入" style="width: 270px">
                    </el-input>
                  </el-form-item>
                  <el-form-item label="型号" prop="Model">
                    <el-input v-model="CreateProductBillForm.Model" placeholder="请输入" style="width: 270px">
                    </el-input>
                  </el-form-item>
                  <el-form-item label="功能" prop="Function">
                    <el-input v-model="CreateProductBillForm.Function" placeholder="请输入" style="width: 270px">
                    </el-input>
                  </el-form-item>
                  <el-form-item label="颜色" prop="Color">
                    <el-input v-model="CreateProductBillForm.Color" placeholder="请输入" style="width: 270px">
                    </el-input>
                  </el-form-item>
                  <el-form-item label="重量" prop="Weight">
                    <el-input v-model="CreateProductBillForm.Weight" placeholder="请输入" style="width: 270px">
                    </el-input>
                  </el-form-item>
                  <el-form-item label="电压" prop="Voltage">
                    <el-input v-model="CreateProductBillForm.Voltage" placeholder="请输入" style="width: 270px">
                    </el-input>
                  </el-form-item>
                  <el-form-item label="电池类型" prop="BatteryType">
                    <el-input v-model="CreateProductBillForm.BatteryType" placeholder="请输入" style="width: 270px">
                    </el-input>
                  </el-form-item>
                  <el-form-item label="充电协议" prop="ChargingProtocol">
                    <el-input
                      v-model="CreateProductBillForm.ChargingProtocol"
                      placeholder="请输入"
                      style="width: 270px"
                    >
                    </el-input>
                  </el-form-item>
                  <!-- <el-form-item label="品牌" prop="Brand">
                <el-input v-model="CreateProductBillForm.Brand" placeholder="请输入" style="width: 270px"> </el-input>
              </el-form-item> -->
                  <el-form-item label="电池容量（mAh）" prop="BatteryCapacity">
                    <el-input v-model="CreateProductBillForm.BatteryCapacity" placeholder="请输入" style="width: 270px">
                    </el-input>
                  </el-form-item>
                  <el-form-item label="额定容量（mAh）" prop="RatedCapacity">
                    <el-input v-model="CreateProductBillForm.RatedCapacity" placeholder="请输入" style="width: 270px">
                    </el-input>
                  </el-form-item>
                  <el-form-item label="最大输出功率" prop="MaxOutputPower">
                    <el-input v-model="CreateProductBillForm.MaxOutputPower" placeholder="请输入" style="width: 270px">
                    </el-input>
                  </el-form-item>

                  <el-form-item label="计量单位" prop="MeasuringUnitId">
                    <el-select
                      v-model="CreateProductBillForm.MeasuringUnitId"
                      placeholder="请选择"
                      clearable
                      style="width: 270px"
                    >
                      <el-option
                        v-for="option in MeasuringUnitOptions"
                        :key="option.id"
                        :label="option.measuringUnitName"
                        :value="option.id"
                      />
                    </el-select>
                  </el-form-item>

                  <el-form-item label="产品分类" prop="ProductClassifyId">
                    <el-tree-select
                      v-model="CreateProductBillForm.ProductClassifyId"
                      :data="sourceData"
                      filterable
                      style="width: 270px"
                      placeholder="请选择"
                    />
                  </el-form-item>
                  <el-form-item label="销售价" prop="SellingPrice">
                    <el-input-number
                      v-model="CreateProductBillForm.SellingPrice"
                      :precision="2"
                      :step="0.1"
                      :max="99999"
                      style="width: 270px"
                    />
                  </el-form-item>
                  <el-form-item label="工艺路线" prop="CraftBillId">
                    <el-select
                      v-model="CreateProductBillForm.CraftBillId"
                      placeholder="请选择"
                      clearable
                      style="width: 270px"
                      @change="handleCraftBillChange"
                    >
                      <el-option
                        v-for="option in CraftBillOptions"
                        :key="option.key"
                        :label="option.craftBillName"
                        :value="option.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
            <el-divider content-position="left">物料\工序列表</el-divider>

            <!-- 产品明细数据表格 -->
            <el-row>
              <el-col :span="24">
                <el-tabs type="border-card">
                  <el-tab-pane label="BOM组成">
                    <!-- 添加BOM明细按钮 -->
                    <el-row>
                      <el-col :span="24">
                        <div style="margin: 10px 0px">
                          <el-button type="primary" plain @click="addBOMDetia()">添加物料</el-button>
                          <el-button type="danger" plain @click="deleteBOMDetia()">清空列表</el-button>
                        </div>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="24">
                        <el-table
                          :data="CreateProductcurrentPageData"
                          border
                          style="width: 100%"
                          max-height="400px"
                          show-overflow-tooltip
                          empty-text="暂无数据"
                        >
                          <el-table-column type="selection" width="55" />
                          <el-table-column type="index" label="序号" />
                          <el-table-column prop="materialsCode" label="物料编码" />
                          <el-table-column prop="materialsName" label="物料名称" />
                          <el-table-column prop="specification" label="规格" />
                          <el-table-column label="使用比例" align="center">
                            <template #default="scope">
                              <el-input-number v-model="scope.row.UsageRatio" :min="1" :max="9999" size="small" />
                            </template>
                          </el-table-column>
                          <el-table-column fixed="right" label="操作" width="90">
                            <template #default="scope">
                              <el-button
                                type="danger"
                                plain
                                size="small"
                                @click="DeleteCraftMaterialsDetiaSingle(scope.row.id)"
                              >
                                移除
                              </el-button>
                            </template>
                          </el-table-column>
                        </el-table>
                      </el-col>
                    </el-row>

                    <!-- 分页 -->
                    <el-row>
                      <el-col :span="24">
                        <div style="display: flex; justify-content: flex-end; margin-top: 10px">
                          <el-config-provider :locale="zhCn">
                            <el-pagination
                              @size-change="CreateProducthandleSizeChange"
                              @current-change="CreateProducthandleCurrentChange"
                              :current-page="CreateProductcurrentPage"
                              :page-sizes="[10, 20, 50, 100]"
                              :page-size="CreateProductpageSize"
                              layout="total, sizes, prev, pager, next, jumper"
                              :total="CreateProductTotalItems"
                            />
                          </el-config-provider>
                        </div>
                      </el-col>
                    </el-row>
                  </el-tab-pane>
                  <el-tab-pane label="工序组成">
                    <el-row>
                      <el-col :span="24">
                        <el-table
                          :data="ProductCraftBillDetials"
                          border
                          style="width: 100%"
                          max-height="400px"
                          show-overflow-tooltip
                          empty-text="暂无数据"
                        >
                          <el-table-column label="排序">
                            <template #default="scope">
                              <span>第 {{ scope.row.processSort }} 道工序</span>
                            </template>
                          </el-table-column>
                          <el-table-column prop="process.processNo" label="工序编码" />
                          <el-table-column prop="process.processName" label="工序名称" />
                        </el-table>
                      </el-col>
                    </el-row>
                  </el-tab-pane>
                </el-tabs>
              </el-col>
            </el-row>
          </div>
        </el-scrollbar>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="CreateProductBillhandleClose">取消</el-button>
            <el-button type="primary" @click="CreateProductBillDialog(CreateProductBillFormRef)">确认</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 选择工序信息 -->
      <ChildComponent
        :querycolumns="querycolumns"
        :columns="columns"
        :data="SelectMaterialstableData"
        :dialogVisible="SelectMaterialsDialogVisible"
        @selected="handleSelectedMaterialsData"
        @closed="handleDialogClosedMaterials"
        @QueryForm="QueryMaterialsForms"
      />
    </div>

    <!-- 修改产品 -->
    <el-dialog
      v-model="UpdateDialogVisible"
      :fullscreen="isFullScreen"
      width="72%"
      append-to-body
      :show-close="false"
      :before-close="UpdateProductBillhandleClose"
    >
      <template #header="{ titleId, titleClass }">
        <div class="my-header">
          <span :id="titleId" :class="titleClass">修改产品</span>
          <div class="header-buttons">
            <el-icon @click="toggleFullScreen" class="icon-button">
              <FullScreen v-if="!isFullScreen" /><CopyDocument v-else />
            </el-icon>
            <el-icon @click="UpdateProductBillhandleClose" class="icon-button full-screen-btn"><Close /></el-icon>
          </div>
        </div>
      </template>

      <el-scrollbar :max-height="maxHeight + 'px'">
        <div>
          <el-row>
            <el-col :span="24">
              <el-form
                :inline="true"
                ref="UpdateProductBillFormRef"
                :model="UpdateProductBillForm"
                label-width="auto"
                class="demo-form-inline"
                :rules="CreateProductBillRules"
              >
                <el-form-item label="产品编码" prop="ProductBillNo">
                  <el-input
                    v-model="UpdateProductBillForm.ProductBillNo"
                    placeholder="不输入则自动生成"
                    style="width: 270px"
                  >
                  </el-input>
                </el-form-item>
                <el-form-item prop="ProductBillName" label="产品名称">
                  <el-input
                    v-model="UpdateProductBillForm.ProductBillName"
                    placeholder="请输入产品产品名称"
                    style="width: 270px"
                  >
                  </el-input>
                </el-form-item>

                <el-form-item label="尺寸" prop="Dimensions">
                  <el-input v-model="UpdateProductBillForm.Dimensions" placeholder="请输入" style="width: 270px">
                  </el-input>
                </el-form-item>
                <el-form-item label="型号" prop="Model">
                  <el-input v-model="UpdateProductBillForm.Model" placeholder="请输入" style="width: 270px"> </el-input>
                </el-form-item>
                <el-form-item label="功能" prop="Function">
                  <el-input v-model="UpdateProductBillForm.Function" placeholder="请输入" style="width: 270px">
                  </el-input>
                </el-form-item>
                <el-form-item label="颜色" prop="Color">
                  <el-input v-model="UpdateProductBillForm.Color" placeholder="请输入" style="width: 270px"> </el-input>
                </el-form-item>
                <el-form-item label="重量" prop="Weight">
                  <el-input v-model="UpdateProductBillForm.Weight" placeholder="请输入" style="width: 270px">
                  </el-input>
                </el-form-item>
                <el-form-item label="电压" prop="Voltage">
                  <el-input v-model="UpdateProductBillForm.Voltage" placeholder="请输入" style="width: 270px">
                  </el-input>
                </el-form-item>
                <el-form-item label="电池类型" prop="BatteryType">
                  <el-input v-model="UpdateProductBillForm.BatteryType" placeholder="请输入" style="width: 270px">
                  </el-input>
                </el-form-item>
                <el-form-item label="充电协议" prop="ChargingProtocol">
                  <el-input v-model="UpdateProductBillForm.ChargingProtocol" placeholder="请输入" style="width: 270px">
                  </el-input>
                </el-form-item>
                <!-- <el-form-item label="品牌" prop="Brand">
                <el-input v-model="UpdateProductBillForm.Brand" placeholder="请输入" style="width: 270px"> </el-input>
              </el-form-item> -->
                <el-form-item label="电池容量（mAh）" prop="BatteryCapacity">
                  <el-input v-model="UpdateProductBillForm.BatteryCapacity" placeholder="请输入" style="width: 270px">
                  </el-input>
                </el-form-item>
                <el-form-item label="额定容量（mAh）" prop="RatedCapacity">
                  <el-input v-model="UpdateProductBillForm.RatedCapacity" placeholder="请输入" style="width: 270px">
                  </el-input>
                </el-form-item>
                <el-form-item label="最大输出功率" prop="MaxOutputPower">
                  <el-input v-model="UpdateProductBillForm.MaxOutputPower" placeholder="请输入" style="width: 270px">
                  </el-input>
                </el-form-item>

                <el-form-item label="计量单位" prop="MeasuringUnitId">
                  <el-select
                    v-model="UpdateProductBillForm.MeasuringUnitId"
                    placeholder="请选择"
                    clearable
                    style="width: 270px"
                  >
                    <el-option
                      v-for="option in MeasuringUnitOptions"
                      :key="option.id"
                      :label="option.measuringUnitName"
                      :value="option.id"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="产品分类" prop="ProductClassifyId">
                  <el-tree-select
                    v-model="UpdateProductBillForm.ProductClassifyId"
                    :data="sourceData"
                    filterable
                    style="width: 270px"
                    placeholder="请选择"
                  />
                </el-form-item>
                <el-form-item label="销售价" prop="SellingPrice">
                  <el-input-number
                    v-model="UpdateProductBillForm.SellingPrice"
                    :precision="2"
                    :step="0.1"
                    :max="99999"
                    style="width: 270px"
                  />
                </el-form-item>
                <el-form-item label="工艺路线" prop="CraftBillId">
                  <el-select
                    v-model="UpdateProductBillForm.CraftBillId"
                    placeholder="请选择"
                    clearable
                    style="width: 270px"
                    @change="handleCraftBillChange"
                  >
                    <el-option
                      v-for="option in CraftBillOptions"
                      :key="option.key"
                      :label="option.craftBillName"
                      :value="option.id"
                    />
                  </el-select>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
          <el-divider content-position="left">物料\工序列表</el-divider>

          <!-- 产品明细数据表格 -->
          <el-row>
            <el-col :span="24">
              <el-tabs type="border-card">
                <el-tab-pane label="BOM组成">
                  <!-- 添加BOM明细按钮 -->
                  <el-row>
                    <el-col :span="24">
                      <div style="margin: 10px 0px">
                        <el-button type="primary" plain @click="UpdateBOMDetia()">添加物料</el-button>
                        <el-button type="danger" plain @click="deleteUpdateBOMDetia()">清空列表</el-button>
                      </div>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="24">
                      <el-table
                        :data="CreateProductcurrentPageData"
                        border
                        style="width: 100%"
                        max-height="400px"
                        show-overflow-tooltip
                        empty-text="暂无数据"
                      >
                        <el-table-column type="selection" width="55" />
                        <el-table-column type="index" label="序号" />
                        <el-table-column prop="materials.materialsCode" label="物料编码" />
                        <el-table-column prop="materials.materialsName" label="物料名称" />
                        <el-table-column prop="materials.specification" label="规格" />
                        <el-table-column label="使用比例" align="center">
                          <template #default="scope">
                            <el-input-number
                              v-model="scope.row.usageRatio"
                              :min="1"
                              :max="9999"
                              size="small"
                              @change="updatehandleUsageRatioChange(scope.row)"
                            />
                          </template>
                        </el-table-column>
                        <el-table-column fixed="right" label="操作" width="90">
                          <template #default="scope">
                            <el-button
                              type="danger"
                              plain
                              size="small"
                              @click="DeleteUpdateCraftMaterialsDetiaSingle(scope.row.id)"
                            >
                              移除
                            </el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                    </el-col>
                  </el-row>

                  <!-- 分页 -->
                  <el-row>
                    <el-col :span="24">
                      <div style="display: flex; justify-content: flex-end; margin-top: 10px">
                        <el-config-provider :locale="zhCn">
                          <el-pagination
                            @size-change="CreateProducthandleSizeChange"
                            @current-change="CreateProducthandleCurrentChange"
                            :current-page="CreateProductcurrentPage"
                            :page-sizes="[10, 20, 50, 100]"
                            :page-size="CreateProductpageSize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="CreateProductTotalItems"
                          />
                        </el-config-provider>
                      </div>
                    </el-col>
                  </el-row>
                </el-tab-pane>
                <el-tab-pane label="工序组成">
                  <el-row>
                    <el-col :span="24">
                      <el-table
                        :data="ProductCraftBillDetials"
                        border
                        style="width: 100%"
                        max-height="400px"
                        show-overflow-tooltip
                        empty-text="暂无数据"
                      >
                        <el-table-column label="排序">
                          <template #default="scope">
                            <span>第 {{ scope.row.processSort }} 道工序</span>
                          </template>
                        </el-table-column>
                        <el-table-column prop="process.processNo" label="工序编码" />
                        <el-table-column prop="process.processName" label="工序名称" />
                      </el-table>
                    </el-col>
                  </el-row>
                </el-tab-pane>
              </el-tabs>
            </el-col>
          </el-row>
        </div>
      </el-scrollbar>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="UpdateProductBillhandleClose">取消</el-button>
          <el-button type="primary" @click="UpdateProductBillDialog(UpdateProductBillFormRef)">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选择工序信息 -->
    <ChildComponent
      :querycolumns="querycolumns"
      :columns="columns"
      :data="SelectMaterialstableData"
      :dialogVisible="UpdateSelectMaterialsDialogVisible"
      @selected="UpdatehandleSelectedMaterialsData"
      @closed="handleDialogClosedMaterials"
      @QueryForm="QueryMaterialsForms"
    />
  </div>
</template>


<script setup lang="ts">
import ChildComponent from '@/components/CustomSelectDataDialog.vue'

import { ApiGetProductPlanning_MaterialPageListAsync } from '../../api/productPlanning/ProductPlanningMaterialApi'
import {
  ApiGetProcessRoute_CraftBillPageListAsync,
  ApiGetProcessRoute_CraftBillDetialsPageListAsync
} from '../../api/processRoute/ProcessRouteCraftBillApi'
import { ApiGetBasicData_MeasuringUnitPageListAsync } from '@/api/basic/basicDataMeasuringUnitApi'
import { ref, reactive, onMounted, computed, onBeforeUnmount } from 'vue'
import { Search } from '@element-plus/icons-vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { ElMessageBox, ElNotification, FormInstance } from 'element-plus'
import {
  ApiGetProductPlanning_ProductBillPageListAsync,
  ApiGetProductPlanning_ProductBillByIdListAsync,
  ApiUpdateProductPlanning_ProductBillDetialAsync,
  ApiDeletionProductPlanning_ProductBillDetialAsync,
  ApiDeletionProductPlanning_ProductBillAsync,
  ApiCreateProductPlanning_ProductBillAsync,
  ApiCreateProductPlanning_ProductBillDetialAsync,
  ApiUpdateProductPlanning_ProductBillAsync
} from '../../api/productPlanning/ProductPlanningProductBillApi'

import { ApiGetProductPlanning_ProductClassifyTreeListAsync } from '../../api/productPlanning/ProductPlanningProductClassifyApi'
import { formatTime, capitalizeFirstLetter } from '../../utils/index'

// 关闭创建产品对话框
const CreateProductBillhandleClose = () => {
  const formEl = CreateProductBillFormRef.value
  if (!formEl) return
  formEl.resetFields()
  centerDialogVisible.value = false //添加对话框状态
  ProductCraftBillDetials.value = [] //工序列表
  MaterialsRouteCraftBillDetial.value = [] //BOM列表
  setTimeout(() => {
    isFullScreen.value = false //添加对话框展开
  }, 300)
}

// 打开添加产品对话框
const addProductBill = () => {
  centerDialogVisible.value = true

  // 获取分类列表
  ApiGetProductPlanning_ProductClassifyTreeListAsync(queryProductClassifyParam).then((res) => {
    sourceData.value = res.data.data
  })

  // 获取计量单位
  ApiGetBasicData_MeasuringUnitPageListAsync(queryMeasuringUnitParam).then((res) => {
    MeasuringUnitOptions.value = res.data.data
  })

  // 获取工艺路线
  ApiGetProcessRoute_CraftBillPageListAsync(queryCraftBillParam).then((res) => {
    CraftBillOptions.value = res.data.data
  })
}

// 确认添加产品
const CreateProductBillDialog = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      const ProductBillDetial = MaterialsRouteCraftBillDetial.value.map((item) => ({
        MaterialsId: item.id,
        UsageRatio: item.UsageRatio
      }))
      CreateProductBillForm.ProductPlanningProductBillDetials = ProductBillDetial
      ApiCreateProductPlanning_ProductBillAsync(CreateProductBillForm).then((res) => {
        if (res.data.data) {
          ElNotification({
            message: '创建成功',
            offset: 100,
            type: 'success',
            duration: 2000
          })
          CreateProductBillhandleClose()
          SearchProductBill()
        }
      })
    }
  })
}

//修改下清空BOM
const deleteUpdateBOMDetia = () => {
  ApiDeletionProductPlanning_ProductBillDetialAsync(MaterialsRouteCraftBillDetial.value.map((g) => g.id)).then(
    (res) => {
      if (res.data.data) {
        ApiGetProductPlanning_ProductBillByIdListAsync(UpdateProductBillForm.Id).then((res) => {
          MaterialsRouteCraftBillDetial.value = res.data.data.productPlanningProductBillDetials
        })
        ElNotification({
          message: `删除成功`,
          offset: 100,
          type: 'success',
          duration: 2000
        })
      }
    }
  )
}

//修改单个移除BOM
const DeleteUpdateCraftMaterialsDetiaSingle = (res: object) => {
  ApiDeletionProductPlanning_ProductBillDetialAsync([res]).then((res) => {
    if (res.data.data) {
      ApiGetProductPlanning_ProductBillByIdListAsync(UpdateProductBillForm.Id).then((res) => {
        MaterialsRouteCraftBillDetial.value = res.data.data.productPlanningProductBillDetials
      })
      ElNotification({
        message: `删除成功`,
        offset: 100,
        type: 'success',
        duration: 2000
      })
    }
  })
}

//修改使用比例
const updatehandleUsageRatioChange = (res: object) => {
  ApiUpdateProductPlanning_ProductBillDetialAsync(res)
}

const ProductBillDetials = ref([{}])

//选择工序对话框确定操作
const UpdatehandleSelectedMaterialsData = (selectedData: Materials[]) => {
  let addedCount = 0
  ProductBillDetials.value = []

  selectedData.forEach((item) => {
    ProductBillDetials.value.push({
      UsageRatio: 1,
      ProductBillId: UpdateProductBillForm.Id,
      MaterialsId: item.id
    })
    addedCount++
  })

  if (ProductBillDetials.value && ProductBillDetials.value.length > 0) {
    ApiCreateProductPlanning_ProductBillDetialAsync(ProductBillDetials.value).then((res) => {
      if (res.data.data) {
        ApiGetProductPlanning_ProductBillByIdListAsync(UpdateProductBillForm.Id).then((res) => {
          MaterialsRouteCraftBillDetial.value = res.data.data.productPlanningProductBillDetials
        })
        ElNotification({
          message: `成功添加 ${addedCount} 条数据`,
          offset: 100,
          type: 'success',
          duration: 2000
        })
      }
    })
  }
}

// 关闭修改产品对话框
const UpdateProductBillhandleClose = () => {
  UpdateDialogVisible.value = false //添加对话框状态
  ProductCraftBillDetials.value = [] //工序列表
  MaterialsRouteCraftBillDetial.value = [] //BOM列表
  setTimeout(() => {
    isFullScreen.value = false //添加对话框展开
  }, 300)
}

// 处理 Name 列点击事件
const handleProductBillNoClick = (row: string) => {
  // 获取分类列表
  ApiGetProductPlanning_ProductClassifyTreeListAsync(queryProductClassifyParam).then((res) => {
    sourceData.value = res.data.data
  })

  // 获取计量单位
  ApiGetBasicData_MeasuringUnitPageListAsync(queryMeasuringUnitParam).then((res) => {
    MeasuringUnitOptions.value = res.data.data
  })

  // 获取工艺路线
  ApiGetProcessRoute_CraftBillPageListAsync(queryCraftBillParam).then((res) => {
    CraftBillOptions.value = res.data.data
  })

  ApiGetProductPlanning_ProductBillByIdListAsync(row).then((res) => {
    Object.assign(UpdateProductBillForm, capitalizeFirstLetter(res.data.data))
    MaterialsRouteCraftBillDetial.value = res.data.data.productPlanningProductBillDetials
    ProductCraftBillDetials.value = res.data.data.processRouteCraftBillDetial
  })
  UpdateDialogVisible.value = true
}

// 创建一个响应式变量 maxHeight，初始值为屏幕高度的 80%
const maxHeight = ref(window.innerHeight * 0.6)

// 用于更新 maxHeight 的值
const updateMaxHeight = () => {
  maxHeight.value = window.innerHeight * 0.6
}

// 在组件挂载时添加一个事件监听器，监听窗口大小的变化
onMounted(() => {
  window.addEventListener('resize', updateMaxHeight)
})

// 在组件销毁前移除事件监听器，以防止内存泄漏
onBeforeUnmount(() => {
  window.removeEventListener('resize', updateMaxHeight)
})

const isFullScreen = ref(false)

//展开添加产品窗口
const toggleFullScreen = () => {
  isFullScreen.value = !isFullScreen.value
  if (isFullScreen.value) {
    maxHeight.value = window.innerHeight * 0.8
  } else {
    maxHeight.value = window.innerHeight * 0.6
  }
}

// 分页相关数据
const CreateProductcurrentPage = ref(1)
const CreateProductpageSize = ref(10)

// 计算当前页要显示的数据
const CreateProductcurrentPageData = computed(() => {
  const startIndex = (CreateProductcurrentPage.value - 1) * CreateProductpageSize.value
  const endIndex = Math.min(startIndex + CreateProductpageSize.value, MaterialsRouteCraftBillDetial.value.length)
  return MaterialsRouteCraftBillDetial.value.slice(startIndex, endIndex)
})

// 总条目数
const CreateProductTotalItems = computed(() => MaterialsRouteCraftBillDetial.value.length)

// 处理分页大小变化的方法
const CreateProducthandleSizeChange = (val: number) => {
  CreateProductpageSize.value = val
  CreateProductcurrentPage.value = 1 // 重置页码为 1
}

// 处理当前页变化的方法
const CreateProducthandleCurrentChange = (val: number) => {
  CreateProductcurrentPage.value = val
}

//物料分类选择数据
const sourceData = ref([])
const ProductCraftBillDetials = ref([])

//计量单位查询参数
const queryMeasuringUnitParam = reactive({
  PageIndex: 1,
  PageSize: 9999,
  totalCount: 0
})
const MeasuringUnitOptions = ref([])

//工艺路线查询参数
const queryCraftBillParam = reactive({
  CraftBillName: null,
  PageIndex: 1,
  PageSize: 9999,
  totalCount: 0
})
const CraftBillOptions = ref([])

// 选择BOM信息

interface Materials {
  MaterialsName: string | null
  id: string | null
  UsageRatio: number
  PageIndex: number
  PageSize: number
  totalCount: number
}

const queryMaterialsParam: Materials = reactive({
  MaterialsName: null,
  id: null,
  UsageRatio: 1,
  PageIndex: 1,
  PageSize: 100,
  totalCount: 11
})

// 选择工序查询列
const querycolumns = [{ prop: 'MaterialsName', label: '物料名称' }]

// 选择工序列
const columns = [
  { prop: 'materialsCode', label: '物料编码' },
  { prop: 'materialsName', label: '物料名称' },
  { prop: 'measuringUnitId', label: '计量单位' },
  { prop: 'modelNumber', label: '型号' },
  { prop: 'specification', label: '规格' }
]
const SelectMaterialsDialogVisible = ref(false)
const UpdateSelectMaterialsDialogVisible = ref(false)

//选择工序表格数据
const SelectMaterialstableData = ref([])
const MaterialsRouteCraftBillDetial = ref<Materials[]>([])

//打开添加BOM
const addBOMDetia = () => {
  SelectMaterialsDialogVisible.value = true

  //获取物料列表
  ApiGetProductPlanning_MaterialPageListAsync(queryMaterialsParam).then((res) => {
    SelectMaterialstableData.value = res.data.data
  })
}

//打开修改BOM窗口
const UpdateBOMDetia = () => {
  UpdateSelectMaterialsDialogVisible.value = true

  //获取物料列表
  ApiGetProductPlanning_MaterialPageListAsync(queryMaterialsParam).then((res) => {
    SelectMaterialstableData.value = res.data.data
  })
}

// 对话框关闭后执行的逻辑
const handleDialogClosedMaterials = () => {
  SelectMaterialsDialogVisible.value = false
  UpdateSelectMaterialsDialogVisible.value = false
}

//选择工序对话框确定操作
const handleSelectedMaterialsData = (selectedData: Materials[]) => {
  let duplicateCount = 0
  let addedCount = 0

  selectedData.forEach((item) => {
    if (MaterialsRouteCraftBillDetial.value && Array.isArray(MaterialsRouteCraftBillDetial.value)) {
      if (!MaterialsRouteCraftBillDetial.value.some((data) => data.id === item.id)) {
        item.UsageRatio = 1
        MaterialsRouteCraftBillDetial.value.push(item)
        addedCount++
      } else if (Array.isArray(MaterialsRouteCraftBillDetial.value)) {
        duplicateCount++
      }
    } else {
      // 处理ProcessRouteCraftBillDetial.value为null或者非数组的情况
      MaterialsRouteCraftBillDetial.value = selectedData
      addedCount = selectedData.length
    }
  })

  if (duplicateCount > 0) {
    ElNotification({
      message: `存在重复 ${duplicateCount} 条，已成功添加 ${addedCount} 条数据`,
      offset: 100,
      type: 'warning',
      duration: 3500
    })
  } else {
    ElNotification({
      message: `成功添加 ${addedCount} 条数据`,
      offset: 100,
      type: 'success',
      duration: 2000
    })
  }
}

//清空BOM明细
const deleteBOMDetia = () => {
  MaterialsRouteCraftBillDetial.value = []
}

//添加BOM明细移除
const DeleteCraftMaterialsDetiaSingle = (rowId: string) => {
  const rowidindex = MaterialsRouteCraftBillDetial.value.findIndex((g) => g.id === rowId)
  if (rowidindex != -1) {
    MaterialsRouteCraftBillDetial.value.splice(rowidindex, 1)
  }
}

//选择工序对话框查询操作
const QueryMaterialsForms = (form: Materials) => {
  ApiGetProductPlanning_MaterialPageListAsync(form).then((res) => {
    SelectMaterialstableData.value = res.data.data
  })
}

//添加产品（选择工艺路线）
//明细查询参
const queryCraftBillDetialsParam = reactive({
  CraftBillName: null,
  CraftBillId: '',
  PageIndex: 1,
  PageSize: 100,
  totalCount: 11
})
const handleCraftBillChange = (newValue: string) => {
  queryCraftBillDetialsParam.CraftBillId = newValue
  ApiGetProcessRoute_CraftBillDetialsPageListAsync(queryCraftBillDetialsParam).then((res) => {
    ProductCraftBillDetials.value = res.data.data
  })
}

// 定义接口和类型
interface ProductBillParam {
  ProductBillsName: string | null
  ProductClassifyId: string | null
  PageIndex: number
  PageSize: number
  totalCount: number
}

interface ProductBill {
  id: string
}

// 响应式变量
const tableloading = ref(false)
const UpdateDialogVisible = ref(false)
const centerDialogVisible = ref(false)
const selectedRows = ref<string[]>([]) // 存储选中的行数据
const CreateProductBillFormRef = ref<FormInstance>()

// 表单数据和验证规则
const CreateProductBillForm = reactive({ id: '', SellingPrice: 1, ProductPlanningProductBillDetials: [] })
const UpdateProductBillForm: ProductBill = reactive({ id: '' })
const CreateProductBillRules = reactive({
  ProductBillName: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
  SellingPrice: [{ required: true, message: '销售价不能为空', trigger: 'blur' }],
  CraftBillId: [{ required: true, message: '工艺路线不能为空', trigger: 'blur' }],
  Model: [{ required: true, message: '型号不能为空', trigger: 'blur' }],
  Weight: [{ required: true, message: '重量不能为空', trigger: 'blur' }],
  Dimensions: [{ required: true, message: '尺寸不能为空', trigger: 'blur' }],
  ProductClassifyId: [{ required: true, message: '产品分类不能为空', trigger: 'blur' }]
})

// 查询参数
const queryProductBillParam: ProductBillParam = reactive({
  ProductBillsName: null,
  ProductClassifyId: null,
  PageIndex: 1,
  PageSize: 100,
  totalCount: 11
})

// 物料分类查询参数
const queryProductClassifyParam = reactive({
  ProductClassifyName: null,
  PageIndex: 1,
  PageSize: 9999,
  totalCount: 0
})

// 表格数据
const tableData = ref([])

//左侧分类列表
const treeData = ref([])

interface defaultProps {
  value: 'name'
  label: 'name'
  children: 'children'
}

// 页面左边树形分类
const handleTreeNodeClick = (nodeData: defaultProps) => {
  queryProductBillParam.ProductClassifyId = nodeData.value
  SearchProductBill()
}

// 搜索产品
const SearchProductBill = () => {
  tableloading.value = true
  ApiGetProductPlanning_ProductBillPageListAsync(queryProductBillParam)
    .then((res) => {
      tableData.value = res.data.data
      queryProductBillParam.PageIndex = res.data.pageIndex
      queryProductBillParam.PageSize = res.data.pageSize
      queryProductBillParam.totalCount = res.data.totalCount
    })
    .finally(() => {
      tableloading.value = false
    })
}

// 打开更新产品信息对话框
// const UpdateProductBill = (row: { [key: string]: string | number }) => {
//   Object.assign(UpdateProductBillForm, capitalizeFirstLetter(row))
//   UpdateDialogVisible.value = true
// }

// 确认更新产品信息
const UpdateProductBillFormRef = ref<FormInstance>()
const UpdateProductBillDialog = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      console.log('UpdateProductBillForm', UpdateProductBillForm)

      ApiUpdateProductPlanning_ProductBillAsync(UpdateProductBillForm).then((res) => {
        if (res.data.data) {
          ElNotification({
            message: '更新成功',
            offset: 100,
            type: 'success',
            duration: 2000
          })
          UpdateProductBillhandleClose()
          SearchProductBill()
        }
      })
    }
  })
}

// 删除单个产品
const DeleteProductBillSingle = (id: string) => {
  selectedRows.value = [id]
  batchDeletionProductBill()
}

// 批量删除产品
const batchDeletionProductBill = () => {
  if (selectedRows.value.length < 1) {
    ElNotification({
      message: '请先选择一条或更多信息',
      type: 'warning',
      offset: 100,
      duration: 2000
    })
    return
  }
  ElMessageBox.confirm('确实要删除这些信息吗?', '删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      ApiDeletionProductPlanning_ProductBillAsync(selectedRows.value)
        .then((res) => {
          if (res.data.data) {
            ElNotification({
              message: '删除成功',
              offset: 100,
              type: 'success',
              duration: 2000
            })
            selectedRows.value = []
            SearchProductBill()
          }
        })
        .catch(() => {
          selectedRows.value = []
        })
    })
    .catch(() => {
      selectedRows.value = []
    })
}

// 获取用户选择项
const handleSelectionChange = (val: ProductBill[]) => {
  selectedRows.value = val.map((item) => item.id)
}

// 时间转换
const formatColumnTime = (row: object, column: string, time: string | number | Date) => {
  if (time === null) {
    return ''
  }

  if (typeof time === 'string' || typeof time === 'number') {
    return formatTime(time)
  } else {
    return formatTime(time.getTime())
  }
}

// 每页条数
const handleSizeChange = (e: number) => {
  queryProductBillParam.PageSize = e
  SearchProductBill()
}

// 当前页变化
const handleCurrentChange = (e: number) => {
  queryProductBillParam.PageIndex = e
  SearchProductBill()
}

// 初次加载数据
onMounted(() => {
  SearchProductBill()

  // 获取分类列表
  ApiGetProductPlanning_ProductClassifyTreeListAsync(queryProductClassifyParam).then((res) => {
    treeData.value = res.data.data
  })
})
</script>



<style lang="less"  scoped>
@import '../../assets/globle/index.css';
.leftcontentarea {
  margin-top: 18px;
  border-right: 10px solid #f0f1f3; /* 设置右边框颜色 */
  padding: 20px 0px 12px 2px;
  span {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 17px;
  }
}
.rightcontentarea {
  .rightcontentareatable {
    margin-top: 18px;
    padding: 2px 2px 2px 15px;
    background-color: #fff;
  }
  .functionbutton {
    padding: 20px 10px 20px 0px;
  }
  .demo-pagination-block {
    padding: 12px 2px 12px 2px;
    right: 0;
  }
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.ep-bg-purple {
  background-color: #fff; /* 修改为你想要的背景颜色 */
}
.x-scrollbar {
  padding: 0px 17px 17px 17px;
}

.my-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  align-items: center;
}

.icon-button {
  margin-left: 10px;
  cursor: pointer;
}

.full-screen-btn {
  margin-left: 10px;
}
</style>
